//
//  UITextView+Emoticon.m
//  XinLang_OC
//
//  Created by Boss Lin on 16/5/17.
//  Copyright © 2016年 cheuhui. All rights reserved.
//

#import "UITextView+Emoticon.h"
#import "Emoticon.h"


@implementation UITextView (Emoticon)


/// 添加一个表情到textView
- (void)insertEmoticon:(Emoticon *)emoction {
    // 判断是否是删除按钮
    if (emoction.removeEmoticon) {
        [self deleteBackward];
        return;
    }

    // 添加emoji表情
    if (emoction.emoji) {
        // 将emoji表情添加到textView上
        [self insertText:emoction.emoji];
        return;
    }
    
    // 添加图片表情
    if (emoction.pngPath) {
        NSAttributedString *attrString = [emoction emoticonToAttrString:self.font];
        // 获取选中的范围
        NSRange sRange = self.selectedRange;
        // 将textView的属性文本 改为 可变
        NSMutableAttributedString *attrM = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
        // 在原有的基础上插入新的表情
        [attrM insertAttributedString:attrString atIndex:sRange.location];
        self.attributedText = attrM;
        
        // 重新设置选中范围，让光标在插入表情后面
        self.selectedRange = NSMakeRange(sRange.location + 1, 0);
        
        // 手动触发textView文本改变
        // 发送通知,文字改变
        [[NSNotificationCenter defaultCenter] postNotificationName:UITextViewTextDidChangeNotification object:self];
        
        // 调用代理,文字改变
        if ([self.delegate respondsToSelector:@selector(textViewDidChange:)]) {
            [self.delegate textViewDidChange:self];
        }
    }
    
}



@end
